package com.jin.webvideo.base.httpclient;

import com.jin.webvideo.base.StringKeyValuePairs;
import com.jin.webvideo.base.util.CollectionsUtil;
import com.jin.webvideo.base.util.ReflectUtil;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.impl.io.EmptyInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ParamHttpEntity extends AbstractHttpEntity {
    private Map<String, List<String>> params = new HashMap<>();

    public ParamHttpEntity(Object object) {
        try {
            Map<String, Object> params = ReflectUtil.toMap(object);
            for (String key : params.keySet()) {
                List list = (List) ReflectUtil.toList(params.get(key));
                List<String> s = CollectionsUtil.convert(list, (obj) -> String.valueOf(obj));
                this.params.put(key, s);
            }
        } catch (ReflectiveOperationException e) {
            e.printStackTrace();
        }
    }
    public URI getURI(URI uri) {
        StringBuilder builder = new StringBuilder();
        for (String key : params.keySet()) {
            List<String> values = params.get(key);
            boolean isEmpty = true;
            for (String val : values) {
                isEmpty = false;
                builder.append( createKv(key, val) );
            }
            if (isEmpty) {
                builder.append( createKv(key, "") );
            }
        }
        StringKeyValuePairs kvp = StringKeyValuePairs.createKeyValuePairs(uri.toString(), "?");
        if (!kvp.getValue().isEmpty()) {
            kvp.setValue(kvp.getValue() + builder.toString());
        }
        else if (!builder.isEmpty()){
            kvp.setValue(builder.substring(1));
        }
        return URI.create(kvp.join("?"));
    }

    private String createKv(String key, String val) {
        return String.format("&%s=%s", key, val);
    }

    @Override
    public boolean isRepeatable() {
        return false;
    }

    @Override
    public long getContentLength() {
        return 0;
    }

    @Override
    public InputStream getContent() throws IOException, UnsupportedOperationException {
        return EmptyInputStream.INSTANCE;
    }

    @Override
    public void writeTo(OutputStream outStream) throws IOException {
    }

    @Override
    public boolean isStreaming() {
        return false;
    }
}
